package letsjava.mail;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import letsjava.utils.NSConfig;

public class MailSend {
	public static void main(String[] args) throws Exception {
		HashMap<String, String> config = NSConfig.getConfig();
		String smtp_test_mail = config.get("smtp_test_mail");
		try {
			MailSend.sendMail(smtp_test_mail, "hello", "world");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void sendMail(String mailto, String subject, String body)
	        throws SendFailedException {
		try {
			HashMap<String, String> config = NSConfig.getConfig();
			String smtp_login_user = config.get("smtp_login_user");
			String smtp_login_pass = config.get("smtp_login_pass");
			String smtp_from_name = config.get("smtp_from_name");
			String smtp_from = config.get("smtp_from");
			String smtp_host = config.get("smtp_host");

			Properties props = new Properties();// 获取系统环境
			Authenticator auth = new Email_Autherticator(smtp_login_user,
			        smtp_login_pass);// 进行邮件服务用户认证
			props.put("mail.smtp.host", smtp_host);
			props.put("mail.smtp.auth", "true");
			//System.out.println(props);
			//System.out.println(config);
			Session session = Session.getDefaultInstance(props, auth);
			// 设置session,和邮件服务器进行通讯
			MimeMessage message = new MimeMessage(session);
			// message.setContent("11", "text/plain");// 设置邮件格式
			message.setSubject(subject);// 设置邮件主题
			message.setText(body);// 设置邮件内容
			// message.setHeader(mail_head_name, mail_head_value);// 设置邮件标题
			// message.setSentDate(new Date());// 设置邮件发送时期
			Address address = new InternetAddress(smtp_from, smtp_from_name);
			message.setFrom(address);// 设置邮件发送者的地址
			Address toaddress = new InternetAddress(mailto);// 设置邮件接收者的地址
			message.addRecipient(Message.RecipientType.TO, toaddress);
			// message.addRecipient(Message.RecipientType.CC, toaddress);
			System.out.println(message);
			Transport.send(message);
			System.out.println("Send Mail Ok!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return flag;
	}
}